package com.lottery.service.pc28.wealthService.impl;

import com.alibaba.fastjson.JSON;
import com.lottery.dao.pc28.accoutDao.UserDao;
import com.lottery.dao.pc28.bettingDao.BettingLimitationDao;
import com.lottery.dao.pc28.lobbyDao.NoticeDao;
import com.lottery.dao.pc28.wealthDao.AccountDao;
import com.lottery.dao.pc28.wealthDao.AccountTransactionDao;
import com.lottery.dto.DailyBettingSummary;
import com.lottery.dto.ResultDto;
import com.lottery.entity.Account;
import com.lottery.entity.AccountTransaction;
import com.lottery.entity.BettingLimitation;
import com.lottery.entity.Notice;
import com.lottery.service.pc28.wealthService.QueryAccountService;
import com.lottery.service.pc28.wealthService.impl.config.AccountConfig;
import com.lottery.service.pc28.wealthService.impl.config.AccountTransactionConfig;
import com.lottery.service.pc28.wealthService.impl.uitil.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QueryAccountServiceImpl implements QueryAccountService {

	@Resource
	private AccountDao accountdao;

	@Resource
	private AccountTransactionDao accounttransactiondao;

	@Autowired
	private UserDao userdao;

	@Autowired
	private NoticeDao noticeDao;

	@Autowired
	private BettingLimitationDao bettingLimitationDao;

	// 日志
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 财富查询
	 * 
	 * @param user_id
	 * @return
	 */
	@Override
	public String selectAccountConfig(int userId) {
		Map<String, Object> maxMap = new HashMap<>();
		ResultDto<AccountConfig> resultDto = new ResultDto<AccountConfig>();
		try {
			AccountConfig accountConfig = new AccountConfig();
			Account account = accountdao.selectAccountByUserId(userId);
			double account_funds = account.getAccountFunds();// '账户余额',
			DecimalFormat df = new DecimalFormat("#0.##");
			df.setRoundingMode(RoundingMode.FLOOR);
			account_funds = Double.valueOf(df.format(account_funds));
			double account_freeze = account.getAccountFreeze();// '冻结资产',
			account_freeze = Double.valueOf(df.format(account_freeze));
			double general_assets = account_funds + account_freeze;// '账户总资产',
			general_assets = Double.valueOf(df.format(general_assets));
			accountConfig.setAccount_freeze(account_freeze);
			accountConfig.setAccountFunds(account_funds);
			accountConfig.setGeneralAssets(general_assets);

			maxMap.put("array", accountConfig);
			maxMap.put("result", "0");
			maxMap.put("msg", "200");

		} catch (Exception e) {
			logger.error("selectAccountConfig error:", e);
			maxMap.put("result", "1");
			maxMap.put("msg", "异常");
		}
		return JSON.toJSONString(maxMap, true);
	}

	/**
	 * 查询记录
	 * 
	 * @param user_id
	 * @return
	 */
	// money_sources":null,"money_go":null
	@Override
	public String selectWealthRecord(int userId, int types, int startPage, int pageSize) {
		Map<String, Object> maxMap = new HashMap<>();
		List<AccountTransactionConfig> list = new ArrayList<AccountTransactionConfig>();
		String transaction_date_YMD = "";
		String transaction_date_HMS = "";
		String money_sources = "";
		String money_go = "";
		try {
			int accountId = accountdao.selectAccountByUserId(userId).getId();
			List<AccountTransaction> accountTransactionlist = accounttransactiondao
					.selectAccountTransactionByAccountIdLimit(accountId, types, startPage, pageSize);
			if (accountTransactionlist != null) {
				for (AccountTransaction accountTransaction : accountTransactionlist) {
					double transaction_money = accountTransaction.getTransactionMoney();
					transaction_date_YMD = DateUtil.formatDate(accountTransaction.getTransactionDate(), DateUtil.YMD_);
					transaction_date_HMS = DateUtil.formatDate(accountTransaction.getTransactionDate(), DateUtil.HMS_);
					money_sources = accountTransaction.getMoneySources();
					money_go = accountTransaction.getMoneyGo();
					AccountTransactionConfig accountTransactionConfig = new AccountTransactionConfig();
					accountTransactionConfig.setTransactionDateYMD(transaction_date_YMD);
					accountTransactionConfig.setTransactionDateHMS(transaction_date_HMS);
					accountTransactionConfig.setTransactionMoney(transaction_money);
					accountTransactionConfig.setTransactionType(types);
					accountTransactionConfig.setMoneySources(money_sources);
					accountTransactionConfig.setMoneyGo(money_go == null ? "" : money_go);
					accountTransactionConfig.setState(accountTransaction.getState());
					accountTransactionConfig
							.setOrderId(accountTransaction.getOrderId() == null ? "" : accountTransaction.getOrderId());
					accountTransactionConfig
							.setRemark(accountTransaction.getRemarks() == null ? "" : accountTransaction.getRemarks());
					list.add(accountTransactionConfig);
				}
			}
			maxMap.put("array", list);
			maxMap.put("result", "0");
			maxMap.put("msg", "200");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("selectWealthRecord error:", e);
			maxMap.put("result", "1");
			maxMap.put("msg", "400" + e.toString());
		}
		return JSON.toJSONString(maxMap, true);
	}

	/**
	 * 查询用户当日的流水
	 * 
	 * @param user_id
	 * @return
	 */
	@Override
	public String queryDailyBettingSummary(int userId) {
		Map<String, Object> maxMap = new HashMap<>();
		try {
			Account account = new Account();
			account.setUserId(userId);
			DailyBettingSummary pipelining = accountdao.selectDailyBettingSummary(account);
			if (pipelining == null) {
				pipelining = new DailyBettingSummary();
				pipelining.setBettingMoney(0);
				pipelining.setBettingNumber(0);
				pipelining.setIncom(0);
				String money = accounttransactiondao.selectTransactionMoney(userId);
				pipelining.setFallintoMoney(Double.valueOf(money));
				pipelining.setWinningaMount(0);
			} else {
				Double winningamount = accountdao.selectDailyWinningamount(account);
				Double bettingmoney = accountdao.selectDailyBettingmoney(account);
				double incom = winningamount - bettingmoney;
				DecimalFormat df = new DecimalFormat("#0.##");
				df.setRoundingMode(RoundingMode.FLOOR);
				incom = Double.valueOf(df.format(incom));
				String money = accounttransactiondao.selectTransactionMoney(userId);
				pipelining.setFallintoMoney(Double.valueOf(money));
				pipelining.setIncom(incom);
				pipelining.setBettingMoney(Double.valueOf(df.format(pipelining.getBettingMoney())));
				pipelining.setWinningaMount(Double.valueOf(df.format(pipelining.getWinningaMount())));
			}
			maxMap.put("array", pipelining);
			maxMap.put("result", "0");
			maxMap.put("msg", "成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryDailyBettingSummary error:", e);
			maxMap.put("result", "1");
			maxMap.put("msg", e.toString());
		}
		return JSON.toJSONString(maxMap, true);
	}

	/**
	 * 查询提现流水状态接口
	 * 
	 * @param user_id
	 * @return
	 */
	public String queryOrderStatus(int userId, int pageNum, int pageSize) {
		// ResultDto<OrderStatus> resultDto = new ResultDto<OrderStatus>();
		// List<OrderStatus> list = new ArrayList<OrderStatus>();
		Map<String, Object> maxmap = new HashMap<String, Object>();
		try {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			int accountId = accountdao.selectAccountByUserId(userId).getId();
			Map<String, Integer> params = new HashMap<String, Integer>();
			int skip = (pageNum - 1) * pageSize;
			params.put("accountId", accountId);
			params.put("skip", skip);
			params.put("pageSize", pageSize);
			List<AccountTransaction> queryOrderStatuslist = accounttransactiondao.queryOrderStatus(params);
			for (AccountTransaction one : queryOrderStatuslist) {
				Map<String, Object> map = new HashMap<String, Object>();
				String timeYMD = DateUtil.formatDate(one.getTransactionDate(), DateUtil.YMD_);
				String timeHMS = DateUtil.formatDate(one.getTransactionDate(), DateUtil.HMS_);
				String time = timeYMD + " " + timeHMS;
				map.put("orderId", one.getOrderId());
				map.put("time", time);
				map.put("amount", one.getTransactionMoney());
				int state = one.getState();
				switch (state) {
				case 0:
					map.put("state", "处理中");
					break;
				case 1:
					map.put("state", "成功");
					break;
				case 2:
					map.put("state", "失败");
					break;
				default:
					map.put("state", "未知");
				}
				list.add(map);
			}
			maxmap.put("array", list);
			maxmap.put("result", "0");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryOrderStatus error:", e);
			maxmap.put("result", "1");
			maxmap.put("msg", "获取失败");
		}
		return JSON.toJSONString(maxmap, true);
	}

	@Override
	public String totalWithDrawWealth(int userId, String startTime, String endTime) {
		// TODO Auto-generated method stub
		Map<String, Object> maxmap = new HashMap<String, Object>();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userId", userId);
			params.put("startTime", startTime);
			params.put("endTime", endTime);
			int withDrawTotel = accounttransactiondao.totalWithDrawWealth(params);
			int rechargeTotel = accounttransactiondao.totalRechargeWealth(params);
			maxmap.put("totalwithdraw", withDrawTotel);
			maxmap.put("rechargeTotel", rechargeTotel);
			maxmap.put("result", "0");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("totalWithDrawWealth error:", e);
			maxmap.put("result", "1");
			maxmap.put("msg", "获取失败");
		}
		return JSON.toJSONString(maxmap, true);
	}

	/**
	 * 提现流水查询
	 */
	@Override
	public String withDrowQuery(int userId, String startTime, String endTime, int pageNum, int pageSize) {
		Map<String, Object> maxmap = new HashMap<String, Object>();
		List<AccountTransaction> accountTransaction = null;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			int skip = (pageNum - 1) * pageSize;
			Map<String, Object> params = new HashMap<String, Object>();
			List<Integer> transTypes = new ArrayList<Integer>();
			transTypes.add(2);
			transTypes.add(6);

			if (userId != 0) {
				Account account = accountdao.selectAccountByUserId(userId);
				params.put("accountId", account.getId());
			}

			params.put("transactionType", transTypes);
			params.put("skip", skip);
			params.put("pageSize", pageSize);
			if (startTime != null && !startTime.equals("")) {
				params.put("startTime", startTime);
			}
			if (endTime != null && !endTime.equals("")) {
				params.put("endTime", endTime);
			}

			accountTransaction = accounttransactiondao.selectTranstionList(params);

			for (AccountTransaction one : accountTransaction) {
				Map<String, Object> map = new HashMap<String, Object>();
				Account account = accountdao.selectAccountById(one.getAccountId());
				map.put("userId", account.getUserId());
				map.put("orderId", one.getOrderId());
				String state = "";
				switch (one.getState()) {
				case 0:
					state = "未处理";
					break;
				case 1:
					state = "成功";
					break;
				case 2:
					state = "失败";
					break;
				case 3:
					state = "未知";
					break;
				default:
					state = "未知";
					break;
				}
				map.put("state", state);

				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 转时间格式
				String time = format.format(one.getTransactionDate());
				map.put("transTime", time);

				DecimalFormat df = new DecimalFormat("#.##");
				double transMoney = Double.parseDouble(df.format(one.getTransactionMoney()));
				map.put("transMoney", Double.toString(transMoney));

				String transType = "";
				switch (one.getTransactionType()) {
				case 2:
					transType = "客服提现";
					break;
				case 6:
					transType = "自助提现";
					break;
				default:
					transType = "未知";
					break;
				}
				map.put("transType", transType);
				map.put("operator", one.getOperator());

				map.put("commission", one.getFee());
				map.put("finishTime", one.getFinishTime());
				map.put("remark", one.getRemarks());

				/********** 提现后的金额 ************/
				Map<String, Object> chargeParam = new HashMap<String, Object>();
				chargeParam.put("accountId", one.getAccountId());
				chargeParam.put("endTime", time);
				List<Integer> transTypes1 = new ArrayList<Integer>();
				transTypes1.add(1);
				transTypes1.add(4);
				transTypes1.add(5);
				transTypes1.add(7);
				chargeParam.put("transactionType", transTypes1);
				double sum = accounttransactiondao.selectSumAmountWithDrow(chargeParam);
				transTypes1.clear();
				transTypes1.add(2);
				transTypes1.add(3);
				transTypes1.add(6);
				chargeParam.put("transactionType", transTypes1);
				double sum1 = accounttransactiondao.selectSumAmountWithDrow(chargeParam);
				double ba = sum - sum1;
				ba = Double.parseDouble(df.format(ba));
				map.put("beforewithDrowMoney", "-");
				map.put("afterwithDrowMoney", Double.toString(ba));
				/****************************************/

				map.put("cashAccount", one.getCashAccout() == null ? "" : one.getCashAccout());
				map.put("cashName", one.getCashName() == null ? "" : one.getCashName());
				list.add(map);
			}
			maxmap.put("array", list);
			maxmap.put("result", "0");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("withDrowQuery error:", e);
			maxmap.put("result", "1");
			maxmap.put("msg", "获取失败");
		}
		return JSON.toJSONString(maxmap, true);
	}

	/**
	 * 充值流水查询
	 */
	@Override
	public String rechargeQuery(int userId, String startTime, String endTime, int pageNum, int pageSize) {
		Map<String, Object> maxmap = new HashMap<String, Object>();
		List<AccountTransaction> accountTransaction = null;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			int skip = (pageNum - 1) * pageSize;
			Map<String, Object> params = new HashMap<String, Object>();
			List<Integer> transTypes = new ArrayList<Integer>();
			transTypes.add(1);

			if (userId != 0) {
				Account account = accountdao.selectAccountByUserId(userId);
				params.put("accountId", account.getId());
			}

			params.put("transactionType", transTypes);
			params.put("skip", skip);
			params.put("pageSize", pageSize);
			if (startTime != null && !startTime.equals("")) {
				params.put("startTime", startTime);
			}
			if (endTime != null && !endTime.equals("")) {
				params.put("endTime", endTime);
			}

			accountTransaction = accounttransactiondao.selectTranstionList(params);

			for (AccountTransaction one : accountTransaction) {
				Map<String, Object> map = new HashMap<String, Object>();
				Account account = accountdao.selectAccountById(one.getAccountId());
				map.put("userId", account.getUserId());
				map.put("orderId", one.getOrderId());
				String state = "";
				switch (one.getState()) {
				case 0:
					state = "未处理";
					break;
				case 1:
					state = "成功";
					break;
				case 2:
					state = "失败";
					break;
				case 3:
					state = "未知";
					break;
				default:
					state = "未知";
					break;
				}
				map.put("state", state);

				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 转时间格式
				String time = format.format(one.getTransactionDate());
				map.put("transTime", time);

				DecimalFormat df = new DecimalFormat("#.##");
				double transMoney = Double.parseDouble(df.format(one.getTransactionMoney()));
				map.put("transMoney", Double.toString(transMoney));

				String transType = "客服充值";
				map.put("transType", transType);
				map.put("operator", one.getOperator());
				map.put("remark", one.getRemarks());

				/********** 计算充值前金额和充值后金额 ************/
				Map<String, Object> chargeParam = new HashMap<String, Object>();
				chargeParam.put("accountId", one.getAccountId());
				chargeParam.put("endTime", time);
				List<Integer> transTypes1 = new ArrayList<Integer>();
				transTypes1.add(1);
				transTypes1.add(4);
				transTypes1.add(5);
				transTypes1.add(7);
				chargeParam.put("transactionType", transTypes1);
				double sum = accounttransactiondao.selectSumAmount(chargeParam);
				transTypes1.clear();
				transTypes1.add(2);
				transTypes1.add(3);
				transTypes1.add(6);
				chargeParam.put("transactionType", transTypes1);
				double sum1 = accounttransactiondao.selectSumAmount(chargeParam);
				double ba = sum - sum1;
				ba = Double.parseDouble(df.format(ba));
				map.put("beforeChargeMoney", Double.toString(ba));
				map.put("afterChargeMoney", Double.toString(ba + transMoney));
				/****************************************/
				list.add(map);
			}
			maxmap.put("array", list);
			maxmap.put("result", "0");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("rechargeQuery error:", e);
			maxmap.put("result", "1");
			maxmap.put("msg", "获取失败");
		}
		return JSON.toJSONString(maxmap, true);
	}

	@Override
	public String getRechargeUrl() {
		Map<String, Object> maxmap = new HashMap<String, Object>();
		try {
			BettingLimitation betLimit = bettingLimitationDao.selectMaxMinBet();

			maxmap.put("url", betLimit.getRechargeurl());
			maxmap.put("result", "0");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getRechargeUrl error:", e);
			maxmap.put("result", "1");
			maxmap.put("msg", "获取失败");
		}
		return JSON.toJSONString(maxmap, true);
	}

	@Override
	public String rechargeHint(int userId) {
		// TODO Auto-generated method stub
		Map<String, Object> maxmap = new HashMap<String, Object>();
		try {
			Notice notice = new Notice();
			notice.setUserId(userId);
			notice.setBeread(0);
			List<Notice> li = noticeDao.selectUserNotice(notice);
			String noticeInfos = "";
			for (Notice one : li) {
				noticeInfos = noticeInfos + one.getNoticeInfo() + "\r\n";
			}

			notice.setBeread(1);
			noticeDao.updateUserNotice(notice);

			maxmap.put("noticeInfos", noticeInfos);
			maxmap.put("result", "0");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("rechargeHint error:", e);
			maxmap.put("result", "1");
			maxmap.put("msg", "获取失败");
		}
		return JSON.toJSONString(maxmap, true);
	}

}
